package com.winit.openapi.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.common.BankAccountService;
import com.winit.erp.spi.common.command.BankAccountCommand;
import com.winit.erp.spi.common.command.TranstypeEnum;
import com.winit.erp.spi.common.vo.BankAccount;
import com.winit.erp.spi.warehouse.WarehouseService;
import com.winit.erp.spi.warehouse.command.WarehouseCommand;
import com.winit.erp.spi.warehouse.vo.Warehouse;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.command.QueryWarehouseCommand;
import com.winit.pms.spi.winit.LogisticsdistService;
import com.winit.pms.spi.winit.WinitPostService;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitSlaService;
import com.winit.pms.spi.winit.command.LogisticsDistFindCommand;
import com.winit.pms.spi.winit.command.WinitPostFindCommand;
import com.winit.pms.spi.winit.command.WinitProductFindCommand;
import com.winit.pms.spi.winit.command.WinitProductQueryBySellerCommand;
import com.winit.pms.spi.winit.command.WinitSlaFindCommand;
import com.winit.pms.spi.winit.vo.LogisticsDist;
import com.winit.pms.spi.winit.vo.WinitPost;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.pms.spi.winit.vo.WinitSla;
import com.winit.push.spi.EmailService;
import com.winit.push.spi.command.SendEmailCommand;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.systemrule.CityPostCodeService;
import com.winit.ups.spi.systemrule.CountryService;
import com.winit.ups.spi.systemrule.StateService;
import com.winit.ups.spi.systemrule.command.CityPostCodeCommand;
import com.winit.ups.spi.systemrule.command.CountryCommand;
import com.winit.ups.spi.systemrule.command.StateCommand;
import com.winit.ups.spi.systemrule.vo.CityPostCode;
import com.winit.ups.spi.systemrule.vo.Country;
import com.winit.ups.spi.systemrule.vo.State;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * 基础数据查询 国家、省、城市联动 验货仓 TODO long.yue: Change to the actual description of this
 * class
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月8日     Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/baseData")
public class BaseDataController extends BaseController {

    @Resource
    private WarehouseService    warehouseService;
    @Resource
    private WinitProductService    winitProductService;
    @Resource
    private WinitSlaService    winitSlaService;
    @Resource
    private LogisticsdistService    logisticsdistService;
    @Resource
    private WinitPostService    winitPostService;

    @Resource
    private CountryService      countryService;
    @Resource
    private StateService        stateService;
    @Resource
    private CityPostCodeService cityPostCodeService;
    
    @Autowired
    private BankAccountService bankAccountService;    
    @Resource
    private EmailService       emailService;
    
    @Resource
    private com.winit.ups.spi.warehouse.WarehouseService upsWarehouseService;
    
    public void setStateService(StateService stateService) {
        this.stateService = stateService;
    }

    public void setCityPostCodeService(CityPostCodeService cityPostCodeService) {
        this.cityPostCodeService = cityPostCodeService;
    }

    public void setCountryService(CountryService countryService) {
        this.countryService = countryService;
    }

    public void setWarehouseService(WarehouseService warehouseService) {
        this.warehouseService = warehouseService;
    }
    
    @RequestMapping(value = "/transType")
    public String transType(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (TranstypeEnum type : TranstypeEnum.values()) {
            Map<String, String> r1 = new HashMap<String, String>();
            r1.put("key", type.getKey());
            r1.put("name", type.getName());
            r1.put("desc", type.getDesc());
            list.add(r1);
        }
        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/countryList")
    public String countryList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        JSONObject json = (JSONObject) requestMsg.getData();
        CountryCommand command = new CountryCommand();

        if (isExistValue(json, "countryCode")) command.setCountryCode(json.getString("countryCode"));

        List<Country> countryList = countryService.getCountryList(command);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Country co : countryList) {
            Map<String, String> r1 = new HashMap<String, String>();
            r1.put("countryID", String.valueOf(co.getCountryId()));
            r1.put("countryCode", co.getCountryCode());
            r1.put("countryName", co.getCountryName());
            list.add(r1);
        }
        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/provinceList")
    public String provinceList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        long countryID = 0;
        StateCommand command = new StateCommand();
        if (!isExistValue(json, "countryID")) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "countryID");
        }
        if (ValidateUtil.isIntNumber(json.getString("countryID"))) {
            countryID = Long.parseLong(json.getString("countryID"));
            command.setCountryId(countryID);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "countryID");
        }
        List<State> stateList = stateService.findStateList(command);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (State s : stateList) {
            Map<String, String> r1 = new HashMap<String, String>();
            r1.put("provinceID", String.valueOf(s.getStateId()));
            r1.put("provinceCode", s.getStateCode());
            r1.put("provinceName", s.getStateName());
            list.add(r1);
        }
        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/cityList")
    public String cityList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        long stateID = 0;
        CityPostCodeCommand command = new CityPostCodeCommand();
        if (json.containsKey("provinceID")) {
            stateID = Long.parseLong(json.getString("provinceID"));
            command.setStateId(stateID);
        }
        List<CityPostCode> cityList = cityPostCodeService.findCityPostCodeList(command);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (CityPostCode ci : cityList) {
            Map<String, String> r1 = new HashMap<String, String>();
            r1.put("cityID", String.valueOf(ci.getCityPostcodeId()));
            r1.put("cityName", ci.getCityName());
            list.add(r1);
        }
        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/inspWarehouseList")
    public String inspWarehouseList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "productCode");
        ValidateUtil.validMaxLength(json, "productCode", 50);
        
        //productCatalogName默认为ISP服务类型
        String productCatalogName = ApiConstant.PRODUCT_CATALOG_ISP;
        if(ValidateUtil.isNotNull(json, "productCatalogName")){
            ValidateUtil.validMaxLength(json, "productCatalogName", 20);
        	productCatalogName = json.getString("productCatalogName");
        }
        
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        /**********************先获取产品类型为ISP的万邑通产品****************************/
        if(null == CommandContext.getContext()){
            return ERROR;
        }
        if(null == CommandContext.getContext().getOrgId()){
            return ERROR;
        }
        WinitProductFindCommand productCommand = new WinitProductFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        //查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        //按组织ID查询
        searchable.and(SearchFilterHelper.newCondition("ORGANIZATION_ID", SearchOperator.eq, CommandContext.getContext().getOrgId()));
        searchable.and(SearchFilterHelper.newCondition("PRODUCT_CATALOG_NAME", SearchOperator.eq,productCatalogName));
        searchable.and(SearchFilterHelper.newCondition("CODE", SearchOperator.eq, json.getString("productCode")));
        productCommand.setSearchable(searchable);
        Page<WinitProduct> page = winitProductService.findProduct(productCommand);
        if(null == page){
            return ERROR;
        }
        List<WinitProduct> productList = page.getContent();
        if(null == productList || productList.size() < 1){
            return ERROR;
        }
        
        /**********************获取万邑通产品SLA****************************/
        List<Long> slaList = getSLAOrigin(productList);
        if(null == slaList || slaList.size() < 1){
            return ERROR;
        }
        
        /**********************获取万邑通产品分区类型为“Warehouse”的物流分区****************************/
        List<Long> logisticList = getLogistic(slaList);
        if(null == logisticList || logisticList.size() < 1){
            return ERROR;
        }
        
        /**********************获取万邑通产品分区邮编****************************/
        List<String> postalList = getPostal(logisticList);
        if(null == postalList || postalList.size() < 1){
            return ERROR;
        }
        
        /**********************比较物流分区邮编和仓库邮编****************************/
        WarehouseCommand command = new WarehouseCommand();
        List<Warehouse> warehouseList = warehouseService.getWarehouseList(command);
        if(null == warehouseList || warehouseList.size() < 1){
            return ERROR;
        }
        for (Warehouse w : warehouseList) {
            if(StringUtils.isNotBlank(w.getPostal()) && postalList.contains(w.getPostal())){
                Map<String, String> r1 = new HashMap<String, String>();
                r1.put("warehouseID", w.getWarehouseId());
                r1.put("warehouseCode",w.getValue());
                r1.put("warehouseName", w.getName());
                r1.put("warehouseAddress", w.getAddress1());
                list.add(r1);
            }
        }
        responseMsg.setData(list);
        
        return SUCCESS;
    }
    
    @RequestMapping(value = "/getISPWarehouseList")
    public String getISPWarehouseList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        ValidateUtil.validNotNull(json, "productCode");
        ValidateUtil.validMaxLength(json, "productCode", 50);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        if(null == CommandContext.getContext()){
            return ERROR;
        }
        if(null == CommandContext.getContext().getOrgId()){
            return ERROR;
        }
        QueryWarehouseCommand command =new QueryWarehouseCommand();
        command.setCtx(CommandContext.getContext());
        command.setWinitProductCode(StringUtils.trim(json.getString("productCode")));
        List<Warehouse>  warehouseList = winitProductService.getISPWarehouseByWinitProductCode(command);
        if(warehouseList!=null&&warehouseList.size()>0){
            for (Warehouse w : warehouseList) {
                Map<String, String> r1 = new HashMap<String, String>();
                r1.put("warehouseID", w.getWarehouseId());
                r1.put("warehouseCode",w.getValue());
                r1.put("warehouseName", w.getName());
                r1.put("warehouseAddress", w.getAddress1());
                list.add(r1);
            }
        }
        responseMsg.setData(list);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryInspWarehouse")
    public String queryInspWarehouse(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        String productCode = "";
        String productCatalogName = "";
        if (null != requestMsg.getData() && StringUtils.isNotBlank(requestMsg.getData().toString())) {
            JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
            if (ValidateUtil.isNotNull(json, "productCode")) {
                productCode = json.getString("productCode");
            }
            // productCatalogName默认为ISP服务类型
            if (ValidateUtil.isNotNull(json, "productCatalogName")) {
                productCatalogName = json.getString("productCatalogName");
            }
        }

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        /********************** 先获取产品类型为ISP的万邑通产品 ****************************/
        if (null == CommandContext.getContext()) {
            return ERROR;
        }
        if (null == CommandContext.getContext().getOrgId()) {
            return ERROR;
        }
        WinitProductFindCommand productCommand = new WinitProductFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        // 查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        // 按组织ID查询
        searchable.and(SearchFilterHelper.newCondition("ORGANIZATION_ID",
            SearchOperator.eq,
            CommandContext.getContext().getOrgId()));
        if (StringUtils.isNotBlank(productCode)) {
            searchable.and(SearchFilterHelper.newCondition("CODE", SearchOperator.eq, productCode));
        }
        if (StringUtils.isNotBlank(productCatalogName)) {
            searchable.and(SearchFilterHelper.newCondition("PRODUCT_CATALOG_NAME",
                SearchOperator.eq,
                productCatalogName));
        }
        productCommand.setSearchable(searchable);
        Page<WinitProduct> page = winitProductService.findProduct(productCommand);
        if (null == page) {
            return ERROR;
        }
        List<WinitProduct> productList = page.getContent();
        if (null == productList || productList.size() < 1) {
            return ERROR;
        }

        /********************** 获取万邑通产品SLA ****************************/
        List<Long> slaList = getSLAOrigin(productList);
        if (null == slaList || slaList.size() < 1) {
            return ERROR;
        }

        /********************** 获取万邑通产品分区类型为“Warehouse”的物流分区 ****************************/
        List<Long> logisticList = getLogistic(slaList);
        if (null == logisticList || logisticList.size() < 1) {
            return ERROR;
        }

        /********************** 获取万邑通产品分区邮编 ****************************/
        List<String> postalList = getPostal(logisticList);
        if (null == postalList || postalList.size() < 1) {
            return ERROR;
        }

        /********************** 比较物流分区邮编和仓库邮编 ****************************/
        WarehouseCommand command = new WarehouseCommand();
        List<Warehouse> warehouseList = warehouseService.getWarehouseList(command);
        if (null == warehouseList || warehouseList.size() < 1) {
            return ERROR;
        }
        for (Warehouse w : warehouseList) {
            if (StringUtils.isNotBlank(w.getPostal()) && postalList.contains(w.getPostal())) {
                Map<String, String> r1 = new HashMap<String, String>();
                r1.put("warehouseID", w.getWarehouseId());
                r1.put("warehouseCode", w.getValue());
                r1.put("warehouseName", w.getName());
                r1.put("warehouseAddress", w.getAddress1());
                list.add(r1);
            }
        }
        responseMsg.setData(list);

        return SUCCESS;
    }
    
    /**
     * 
     * 优化queryInspWarehouse性能问题
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryInspWarehouse2")
    public String queryInspWarehouse2(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        String productCode = "";
        String productCatalogName = "";
        if (null != requestMsg.getData() && StringUtils.isNotBlank(requestMsg.getData().toString())) {
            JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
            if (ValidateUtil.isNotNull(json, "productCode")) {
                productCode = json.getString("productCode");
            }
            // productCatalogName默认为ISP服务类型
            if (ValidateUtil.isNotNull(json, "productCatalogName")) {
                productCatalogName = json.getString("productCatalogName");
            }
        }

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        /********************** 先获取产品类型为ISP的万邑通产品 ****************************/
        if (null == CommandContext.getContext()) {
            return ERROR;
        }
        if (null == CommandContext.getContext().getOrgId()) {
            return ERROR;
        }
        WinitProductFindCommand productCommand = new WinitProductFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        // 查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        // 按组织ID查询
        searchable.and(SearchFilterHelper.newCondition("ORGANIZATION_ID",
            SearchOperator.eq,
            CommandContext.getContext().getOrgId()));
        if (StringUtils.isNotBlank(productCode)) {
            searchable.and(SearchFilterHelper.newCondition("CODE", SearchOperator.eq, productCode));
        }
        if (StringUtils.isNotBlank(productCatalogName)) {
            searchable.and(SearchFilterHelper.newCondition("PRODUCT_CATALOG_NAME",
                SearchOperator.eq,
                productCatalogName));
        }
        productCommand.setSearchable(searchable);
        Page<WinitProduct> page = winitProductService.findProduct(productCommand);
        if (null == page) {
            return ERROR;
        }
        List<WinitProduct> productList = page.getContent();
        if (null == productList || productList.size() < 1) {
            return ERROR;
        }
        
        List<Long> productIdList  = new ArrayList<Long>();
        for(WinitProduct winitProduct:productList){
            productIdList.add(winitProduct.getWinitProductId());
        }

        /********************** 获取万邑通产品分区类型为“Warehouse”的物流分区 ****************************/
        List<Long> logisticList = getLogisticByProductId(productIdList);
        if (null == logisticList || logisticList.size() < 1) {
            return ERROR;
        }

        /********************** 获取万邑通产品分区邮编 ****************************/
        List<String> postalList = getPostal(logisticList);
        if (null == postalList || postalList.size() < 1) {
            return ERROR;
        }

        /********************** 比较物流分区邮编和仓库邮编 ****************************/
        CodeCommand command = new CodeCommand();
        command.setCode("CHECK");
        List<WarehouseVo> warehouseList = upsWarehouseService.queryWarehouseByType(command);
        if (null == warehouseList || warehouseList.size() < 1) {
            return ERROR;
        }
        for (WarehouseVo w : warehouseList) {
            if (StringUtils.isNotBlank(w.getPostal()) && postalList.contains(w.getPostal())) {
                Map<String, String> r1 = new HashMap<String, String>();
                r1.put("warehouseID", w.getWarehouseId().toString());
                r1.put("warehouseCode", w.getCode());
                r1.put("warehouseName", w.getName());
                r1.put("warehouseAddress", w.getAddress()+"("+w.getPostal()+")");
                list.add(r1);
            }
        }
        responseMsg.setData(list);

        return SUCCESS;
    }

    // 判断非必填字段是否有值
    public boolean isExistValue(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
        	 return !"".equals(jsonObject.getString(key).trim());
        }
        return false;
    }
    
    /**
     * 
     * 根据winit产品ID获取SLA起点分区ID集合
     * @param productList
     * @return
     */
    private List<Long> getSLAOrigin(List<WinitProduct> productList){
        List<Long> list = new ArrayList<Long>();
        for (WinitProduct winitProduct : productList) {
            WinitSlaFindCommand command = new WinitSlaFindCommand();
            Searchable<?> searchable = Searchable.newSearchable();
            Date date = new Date();
            searchable.and(SearchFilterHelper.newCondition("EFFECTIVE", SearchOperator.lt, date));
            searchable.and(SearchFilterHelper.newCondition("EXPIRY", SearchOperator.gt, date));
            searchable.and(SearchFilterHelper.newCondition("WINIT_PRODUCT_ID", SearchOperator.eq, winitProduct.getWinitProductId()));
            //查询所有的值
            searchable.setPage(0, Integer.MAX_VALUE);
            command.setSearchable(searchable);
            Page<WinitSla> page = winitSlaService.findWinitSla(command);
            if(null == page || null == page.getContent() || page.getContent().size() < 1){
                continue;
            } else {
                List<WinitSla> slaList = page.getContent();
                for (WinitSla winitSla : slaList) {
                    if(!list.contains(winitSla.getSlaBegian())){
                        list.add(winitSla.getSlaBegian());
                    }
                }
            }
        }
        return list;
    }
    
    /**
     * 
     * 过滤分区类型为warehouse的分区ID
     * @param slaList
     * @return
     */
    private List<Long> getLogistic(List<Long> slaList){
        List<Long> list = new ArrayList<Long>();
        
        LogisticsDistFindCommand command = new LogisticsDistFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        Direction direction = Direction.DESC;
        searchable.addSort(new Sort(direction, "WINIT_LOGISTICSDIST_ID"));
        searchable.and(SearchFilterHelper.newCondition("DISTRICT_TYPE", SearchOperator.eq, ApiConstant.LOGISTIC_TYPE_WAREHOUSE));
        searchable.and(SearchFilterHelper.newCondition("WINIT_LOGISTICSDIST_ID", SearchOperator.in, convertIn(slaList)));
        //查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        command.setSearchable(searchable);
        Page<LogisticsDist> page = logisticsdistService.findLogisticsDist(command);
        if(null != page && null != page.getContent() && page.getContent().size() > 0){
            List<LogisticsDist> logisticsDistList = page.getContent();
            for (LogisticsDist logisticsDist : logisticsDistList) {
                if(!list.contains(logisticsDist.getWinitLogisticsdistId())){
                    list.add(logisticsDist.getWinitLogisticsdistId());
                }
            }
        }
        
        return list;
    }
    
    /**
     * 
     * 过滤分区类型为warehouse的分区ID
     * @param slaList
     * @return
     */
    private List<Long> getLogisticByProductId(List<Long> productIdList){
        List<Long> list = new ArrayList<Long>();
        
        LogisticsDistFindCommand command = new LogisticsDistFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        searchable.and(SearchFilterHelper.newCondition("DISTRICT_TYPE", SearchOperator.eq, ApiConstant.LOGISTIC_TYPE_WAREHOUSE));
        searchable.and(SearchFilterHelper.newCondition("WINIT_PRODUCT_ID", SearchOperator.in, convertIn(productIdList)));
        //查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        command.setSearchable(searchable);
        Page<LogisticsDist> page = logisticsdistService.findLogisticsDist(command);
        if(null != page && null != page.getContent() && page.getContent().size() > 0){
            List<LogisticsDist> logisticsDistList = page.getContent();
            for (LogisticsDist logisticsDist : logisticsDistList) {
                if(!list.contains(logisticsDist.getWinitLogisticsdistId())){
                    list.add(logisticsDist.getWinitLogisticsdistId());
                }
            }
        }
        
        return list;
    }
    
    /**
     * 
     * 获取物流分区的邮编
     * @param logisticList
     * @return
     */
    private List<String> getPostal(List<Long> logisticList){
        List<String> list = new ArrayList<String>();
        WinitPostFindCommand command = new WinitPostFindCommand();
        Searchable<?> searchable = Searchable.newSearchable();
        searchable.and(SearchFilterHelper.newCondition("WINIT_LOGISTICSDIST_ID", SearchOperator.in, convertIn(logisticList)));
        //查询所有的值
        searchable.setPage(0, Integer.MAX_VALUE);
        command.setSearchable(searchable);
        Page<WinitPost> page = winitPostService.findWinitPost(command);
        if(null == page || null == page.getContent() || page.getContent().size() < 1){
            return list;
        }
        for (WinitPost post : page.getContent()) {
            if(!list.contains(post.getCode())){
                list.add(post.getCode());
            }
        }
        return list;
    }
    
    /**
     * 
     * 拼接查询in条件
     * @param slaList
     * @return
     */
    private String convertIn(List<Long> slaList){
        StringBuffer buff = new StringBuffer();
        boolean startFlag = true;
        for (Long logisticId : slaList) {
            if(startFlag){
                buff.append("(").append(logisticId);
                startFlag = false;
            } else {
                buff.append(",").append(logisticId);
            }
        }
        buff.append(")");
        return buff.toString();
    }	
	
    @RequestMapping(value="/queryBankAccount")
    public String queryBankAccount(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg){
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        BankAccountCommand command = new BankAccountCommand();
        command.setCurrencyCode(json.getString("currencyCode"));
        List<BankAccount> list = bankAccountService.findBankAccount(command);
        responseMsg.setData(list);
        return SUCCESS;
    }

    @RequestMapping(value = "/queryInsWarehouse")
    public String queryInsWarehouse(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        WarehouseCommand command = new WarehouseCommand();
        command.setWarehouseType("IW");
        List<Warehouse> warehouses = warehouseService.getWarehouseList(command);
        responseMsg.setData(warehouses);
        return SUCCESS;
    }
    @RequestMapping(value = "/winitSendEmail")
    public String winitSendEmail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        SendEmailCommand command = new SendEmailCommand();
        command.setTo(json.getString("emailTo"));
        command.setSubject(json.getString("emailSubject"));
        command.setBody(json.getString("emailContent"));
        emailService.send(command);
        responseMsg.setData("发送成功");
        return SUCCESS;
    }

    /**
     * 查询所有ISP支持的验货仓和WINIT产品。开发者平台使用
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/queryAllISPProductAndWarehouse")
    public String queryAllInsAndProduct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                       throws ParseException {
        JSONObject json = JSONObject.parseObject(requestMsg.getData() == null ? "" : requestMsg.getData().toString());
        WinitProductQueryBySellerCommand command = new WinitProductQueryBySellerCommand();
        command.setCtx(CommandContext.getContext());
        // TODO lihui update 修改查询入库产品列表默认组织1000000
        command.setOrganizationId(1000000L);
        // 产品分类名称
        if (null != json && ValidateUtil.isNotNull(json, "productCatalogName")) {
            command.setProductCatelogName(json.getString("productCatalogName"));
        } else {
            // 之前默认类型为ISP
            command.setProductCatelogName(ApiConstant.PRODUCT_CATALOG_ISP);
        }
        if (null != json && ValidateUtil.isNotNull(json, "productCatalogLv2")) {
            command.setProductCatalogLv2(json.getString("productCatalogLv2"));
        }
        List<WinitProduct> productList = winitProductService.queryWinitProduct(command);

        List<Long> productIdList = new ArrayList<Long>();
        for (WinitProduct winitProduct : productList) {
            productIdList.add(winitProduct.getWinitProductId());
        }

        /********************** 获取万邑通产品分区类型为“Warehouse”的物流分区 ****************************/
        LogisticsDistFindCommand logisticsDistFindCommand = new LogisticsDistFindCommand();
        Searchable<?> logisticsSearchable = Searchable.newSearchable();
        logisticsSearchable.and(SearchFilterHelper.newCondition("DISTRICT_TYPE",
            SearchOperator.eq,
            ApiConstant.LOGISTIC_TYPE_WAREHOUSE));
        logisticsSearchable.and(SearchFilterHelper.newCondition("WINIT_PRODUCT_ID",
            SearchOperator.in,
            convertIn(productIdList)));
        // 查询所有的值
        logisticsSearchable.setPage(0, Integer.MAX_VALUE);
        logisticsDistFindCommand.setSearchable(logisticsSearchable);
        Page<LogisticsDist> page = logisticsdistService.findLogisticsDist(logisticsDistFindCommand);
        if (null == page || page.getContent() == null || page.getContent().size() < 1) {
            return ERROR;
        }
        List<LogisticsDist> logisticsDistList = page.getContent();
        List<Long> logisticList = new ArrayList<Long>();
        for (LogisticsDist logisticsDist : logisticsDistList) {
            logisticList.add(logisticsDist.getWinitLogisticsdistId());
        }
        /********************** 获取万邑通产品分区邮编 ****************************/
        WinitPostFindCommand winitPostFindCommand = new WinitPostFindCommand();
        Searchable<?> postSearchable = Searchable.newSearchable();
        postSearchable.and(SearchFilterHelper.newCondition("WINIT_LOGISTICSDIST_ID",
            SearchOperator.in,
            convertIn(logisticList)));
        // 查询所有的值
        postSearchable.setPage(0, Integer.MAX_VALUE);
        winitPostFindCommand.setSearchable(postSearchable);
        Page<WinitPost> postPage = winitPostService.findWinitPost(winitPostFindCommand);
        if (null == postPage || postPage.getContent() == null || postPage.getContent().size() < 1) {
            return ERROR;
        }
        Map<String, Set<String>> relationMap = buildRelationship(logisticsDistList, postPage.getContent());

        /********************** 比较物流分区邮编和仓库邮编 ****************************/
        CodeCommand codeCommand = new CodeCommand();
        codeCommand.setCode("CHECK");
        List<WarehouseVo> warehouseList = upsWarehouseService.queryWarehouseByType(codeCommand);
        if (null == warehouseList || warehouseList.size() < 1) {
            return ERROR;
        }
        // 构建返回结果
        List<Map<String, Object>> productMapList = new ArrayList<Map<String, Object>>();
        for (WinitProduct winitProduct : productList) {
            Map<String, Object> productMap = new HashMap<String, Object>();
            Set<String> postSet = relationMap.get(String.valueOf(winitProduct.getWinitProductId()));
            if (postSet != null && postSet.size() > 0) {
                List<Map<String, String>> warehouseMapList = new ArrayList<Map<String, String>>();
                for (WarehouseVo w : warehouseList) {
                    if (StringUtils.isNotBlank(w.getPostal()) && postSet.contains(w.getPostal())) {
                        Map<String, String> r1 = new HashMap<String, String>();
                        r1.put("warehouseID", w.getWarehouseId().toString());
                        r1.put("warehouseCode", w.getCode());
                        r1.put("warehouseName", w.getName());
                        warehouseMapList.add(r1);
                    }
                }
                productMap.put("warehouseList", warehouseMapList);
                productMap.put("winitProductCode", winitProduct.getCode());
                productMap.put("winitProductName", winitProduct.getName());
                productMapList.add(productMap);
            }

        }

        responseMsg.setData(productMapList);

        return SUCCESS;
    }

    private Map<String, Set<String>> buildRelationship(List<LogisticsDist> logisticsDistList, List<WinitPost> postList) {
        Map<String, Set<String>> data = new HashMap<String, Set<String>>();
        for (LogisticsDist logisticsDist : logisticsDistList) {
            Set<String> set = null;
            for (WinitPost winitPost : postList) {
                if (winitPost.getWinitLogisticsdistId().longValue() == logisticsDist.getWinitLogisticsdistId()
                    .longValue()) {
                    set = data.get(String.valueOf(logisticsDist.getWinitProductId()));
                    if (null == set) {
                        set = new HashSet<String>();
                        set.add(winitPost.getCode());
                    } else {
                        set.add(winitPost.getCode());
                    }
                }
            }
            data.put(String.valueOf(logisticsDist.getWinitProductId()), set);
        }

        return data;
    }

}
